package org.kl.bf.web.basic;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.Config;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.report.exporter.AbstractReportFileExporter;
import org.kl.bf.report.exporter.ReportCreater;
import org.kl.bf.service.basic.ConfigService;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

import com.google.common.collect.Lists;

/**
 * 系统配置
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/config")
public class ConfigController extends BasicController {
	@Autowired
	private ConfigService configService;

	@RequiresPermissions("config:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/configList";
	}

	@RequiresPermissions("config:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Map<String, String> dataDetailMap = BasicController.getCurrentUserDataDetail();
		System.out.println(dataDetailMap.toString());
		Page<Config> configs = configService.getPage(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(configs.getContent(), (int) configs.getTotalElements());
	}

	@RequiresPermissions("config:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		List<Config> configs = configService.searchAll(searchParams, sortType, orderType);
		super.export(Config.class, response, configs, "系统配置");
		return null;
	}

	@RequiresPermissions("config:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("config") Config config,
			@RequestParam(value = "detailInserted", required = false) String detailInserted,
			@RequestParam(value = "detailUpdated", required = false) String detailUpdated,
			@RequestParam(value = "detailDeleted", required = false) String detailDeleted, BindingResult result, HttpSession session) {
		if (result.hasErrors()) {
			return ajaxMsg(bindingMsg(result), false, null);
		}
		try {
			configService.save(config, detailInserted, detailUpdated, detailDeleted);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		List<Config> configList = configService.getAll();
		for (Config c : configList) {
			session.getServletContext().setAttribute(c.getConfigNo(), c.getConfigValue());
		}
		return ajaxMsg("编辑成功", true, null);
	}

	@RequiresPermissions({ "config:delete" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		configService.delete(id);
		List<Config> configList = configService.getAll();
		for (Config c : configList) {
			session.getServletContext().setAttribute(c.getConfigNo(), c.getConfigValue());
		}
		return ajaxMsg("删除成功", true, null);
	}

	@RequiresPermissions({ "config:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = configService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	/**
	 * 打印
	 * 
	 * @param designEntrust
	 * @param response
	 */
	@RequiresPermissions("config:print")
	@RequestMapping(value = "print/{id}", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	public void print(@PathVariable("id") String id, @RequestParam(value = "reportType", defaultValue = "pdf") String reportType,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> reportParams = new HashMap<String, Object>();
			reportParams.put("printorName", BasicController.getCurrentUserName());
			ReportCreater.exportFromJasperFile("config", Lists.newArrayList(configService.getOne(id)), reportParams, request, response,
					AbstractReportFileExporter.ReportType.valueOf(reportType.toUpperCase()));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	@RequiresPermissions("config:list")
	@RequestMapping(value = "flush", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String flush() {
		try {
			configService.flushConfig();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ajaxMsg("清除缓存失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("清除缓存成功", true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getConfig(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("config", configService.getOne(id));
		}
	}
}
